package com.wmlive.hhvideo.heihei.personal.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dyuiapi.api.DyUIAPI;
import com.dyuiapi.api.model.ShortVideoInfo;
import com.wmlive.hhvideo.common.base.DcBaseFragment;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.heihei.beans.main.MultiTypeVideoBean;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoItem;
import com.wmlive.hhvideo.heihei.beans.personal.ListOpusResponse;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.fragment.RecommendFragmentNew;
import com.wmlive.hhvideo.heihei.mainhome.activity.VideoListActivity;
import com.wmlive.hhvideo.heihei.personal.RecyclerScrollListener;
import com.wmlive.hhvideo.heihei.personal.adapter.PersonalProductAdapter;
import com.wmlive.hhvideo.heihei.personal.presenter.PersonalProductPresenter;
import com.wmlive.hhvideo.heihei.personal.util.SpaceItemDecoration;
import com.wmlive.hhvideo.heihei.personal.view.IPersonalProductView;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.widget.refreshrecycler.OnRecyclerItemClickListener;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;

/**
 * Created by XueFei on 2017/5/31.
 * <p>
 * 个人主页--作品
 */

public class PersonalProductFragment extends DcBaseFragment implements SwipeRefreshLayout.OnRefreshListener, RefreshRecyclerView.OnLoadMoreListener, IPersonalProductView, OnRecyclerItemClickListener, RecyclerScrollListener {

    @BindView(R.id.rv_list)
    RefreshRecyclerView rcvList;
    @BindView(R.id.tvEmptyMessage)
    TextView tvEmptyMessage;
    @BindView(R.id.ivEmptyImg)
    ImageView ivEmptyImg;

    private TranslateAnimation translateAnimation;//没有作品时，图片的浮动动画

    private PersonalProductAdapter personalProductAdapter;
    private PersonalProductPresenter personalProductPresenter;
    private IPersonalProductView iPersonalProductView;

    private List<ShortVideoInfo> draftBoxList;//草稿箱

    private long user_id;
    private boolean isShowPop = false;//在无数据时，是否显示开拍pop
    private int offset = 0;
    private boolean isLoadMore = false;

    private RecyclerScrollListener mScrollListener;
    private int mScrollY = 0;

    public static PersonalProductFragment newInstance() {
        PersonalProductFragment fragment = new PersonalProductFragment();
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_personal_product_love;
    }

    @Override
    protected void initData() {
        super.initData();

        iPersonalProductView = this;
        personalProductPresenter = new PersonalProductPresenter(iPersonalProductView);
        addPresenter(personalProductPresenter);

        Bundle bundle = getArguments();
        user_id = bundle.getLong("user_id", 0);
        isShowPop = bundle.getBoolean("isShowPop", false);
        int headHeight = bundle.getInt("headHeight", 0);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
        rcvList.setLayoutManager(gridLayoutManager);
        personalProductAdapter = new PersonalProductAdapter(new ArrayList<ShortVideoItem>(), rcvList);
        rcvList.addItemDecoration(new SpaceItemDecoration(8, true));
        rcvList.setAdapter(personalProductAdapter);
        rcvList.setOnRefreshListener(this);
        rcvList.setOnLoadMoreListener(this);
        rcvList.autoRefresh();

        AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, headHeight);
        View view = new LinearLayout(getActivity());
        view.setLayoutParams(params);
        rcvList.setHeader(view);

        personalProductAdapter.setOnRecyclerItemClickListener(this);

        if (AccountUtil.getUserId() == user_id) {
            if (!isShowPop) {
                tvEmptyMessage.setText(R.string.user_no_opus_other);
            }
//            personalProductAdapter.setEmptyStr(R.string.user_no_like_opus);
        } else {
            tvEmptyMessage.setText(R.string.user_other_no_like_opus);
        }

        personalProductAdapter.setShowEmptyView(false);

        rcvList.getRecycleView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(getActivity()).resumeRequests();
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    Glide.with(getActivity()).pauseRequests();
                } else if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    Glide.with(getActivity()).pauseRequests();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (personalProductAdapter.getItemCount() > 3) {
                    mScrollY += dy;
                    if (mScrollListener != null) {
                        mScrollListener.Scrolled(mScrollY, 0);
                    }
                }
            }
        });
    }

    @Override
    protected void onVisible() {
        super.onVisible();

        if (null != rcvList) {
            onRefresh();
        }
    }

    @Override
    public void handlePersonalProductListSucceed(ListOpusResponse response) {
        List<ShortVideoItem> opusList = response.getList_user_opus();
        if (!isLoadMore) {
            draftBoxList = DyUIAPI.getDraftShortVideoInfos(getActivity());
            int draftBoxsize = draftBoxList.size();
            if (draftBoxsize > 0) {
                if (null != personalProductAdapter) {
                    personalProductAdapter.setHaveDraftBox(true);
                    ShortVideoItem shortVideoItem = new ShortVideoItem();
                    shortVideoItem.setOpus_small_cover(draftBoxList.get(0).getFirstVideoClip());
                    opusList.add(0, shortVideoItem);
                }
            } else {
                if (null != personalProductAdapter) {
                    personalProductAdapter.setHaveDraftBox(false);
                }
            }
        }

        personalProductAdapter.addData(!isLoadMore, opusList);

        int size = personalProductAdapter.getDataContainer().size();
        if (isShowPop) {
            if (size > 0) {
                ivEmptyImg.setVisibility(View.GONE);
                if (null != translateAnimation) {
                    translateAnimation.cancel();
                    translateAnimation = null;
                }
            } else {
                ivEmptyImg.setVisibility(View.VISIBLE);
                ivEmptyImgAnimotion();
            }
        } else {
            if (size > 0) {
                tvEmptyMessage.setVisibility(View.GONE);
            } else {
                tvEmptyMessage.setVisibility(View.VISIBLE);
                ViewTreeObserver vto = rcvList.getViewTreeObserver();
                vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        rcvList.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        int rcvListHeight = rcvList.getHeight();
                        int headerHeight = rcvList.getHeader().getHeight();

                        tvEmptyMessage.getLayoutParams().height = rcvListHeight - headerHeight;
                    }
                });
            }
        }

        offset = response.getOffset();
    }

    @Override
    public void handlePersonalProductListFailure(String error_msg) {
        ToastUtil.showToast(error_msg);
        personalProductAdapter.showError(!isLoadMore);
    }

    @Override
    public void onRefresh() {
        reCreateView();
        reCreatePressenter();
        personalProductPresenter.setView(iPersonalProductView);
        isLoadMore = false;
        offset = 0;
        personalProductPresenter.getPersonaProductlList(user_id, offset);
    }

    @Override
    public void onLoadMore() {
        personalProductPresenter.setView(iPersonalProductView);
        isLoadMore = true;
        personalProductPresenter.getPersonaProductlList(user_id, offset);
    }

    @Override
    protected void onSingleClick(View v) {

    }

    @Override
    public void onRecyclerItemClick(int dataPosition, View view, Object data) {
        boolean isHaveDraftBox = personalProductAdapter.isHaveDraftBox();
        if (isHaveDraftBox) {
            if (dataPosition == 0) {
                Navigator.getInstance().navigateToAraftBox(getActivity());
            } else {
                List<ShortVideoItem> shortVideoItemList = personalProductAdapter.getDataContainer();
                shortVideoItemList.remove(0);
                VideoListActivity.startActivity(getActivity(), RecommendFragmentNew.TYPE_USER, MultiTypeVideoBean.createUserParma(user_id, dataPosition - 1, shortVideoItemList));
            }
        } else {
            VideoListActivity.startActivity(getActivity(), RecommendFragmentNew.TYPE_USER, MultiTypeVideoBean.createUserParma(user_id, dataPosition, personalProductAdapter.getDataContainer()));
        }
    }

    @Override
    public void Scrolled(int distance, int pagePosition) {

    }

    @Override
    public void adjustScroll(int scrollHeight, int headerHeight) {
        if (rcvList == null) {
            return;
        }
        mScrollY = headerHeight - scrollHeight;
        rcvList.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (rcvList.getChildCount() > 0) {
                    rcvList.getViewTreeObserver().removeOnPreDrawListener(this);
                    ((GridLayoutManager) rcvList.getLayoutManager()).scrollToPositionWithOffset(0, -mScrollY);
                    return true;
                }
                return false;
            }
        });
    }

    public void getmScrollListener(RecyclerScrollListener scrollListener) {
        mScrollListener = scrollListener;
    }

    /**
     * 重新创建IView
     */
    private void reCreateView() {
        if (null == iPersonalProductView) {
            iPersonalProductView = new IPersonalProductView() {
                @Override
                public void handlePersonalProductListSucceed(ListOpusResponse response) {
                    PersonalProductFragment.this.handlePersonalProductListSucceed(response);
                }

                @Override
                public void handlePersonalProductListFailure(String error_msg) {
                    PersonalProductFragment.this.handlePersonalProductListFailure(error_msg);
                }

                @Override
                public void onRequestDataError(int requestCode, String message) {
                    PersonalProductFragment.super.onRequestDataError(requestCode, message);
                }

                @Override
                public void handleNetError() {
                    PersonalProductFragment.super.handleNetError();
                }
            };
        }
    }

    /**
     * 重新创建presenter
     */
    private void reCreatePressenter() {
        if (null == personalProductPresenter) {
            personalProductPresenter = new PersonalProductPresenter(iPersonalProductView);
            addPresenter(personalProductPresenter);
        }
    }

    /**
     * 没有作品时，图片的浮动动画
     */
    private void ivEmptyImgAnimotion() {
        translateAnimation = new TranslateAnimation(0f, 0f, 0f, -20f);
        translateAnimation.setDuration(800);
        translateAnimation.setRepeatCount(Animation.INFINITE);
        translateAnimation.setRepeatMode(Animation.REVERSE);
        ivEmptyImg.setAnimation(translateAnimation);
        translateAnimation.start();
    }

    /**
     * 账号被踢后,app不退出，再次登录，fragment没有销毁 导致Uuser_id为之前帐号的
     *
     * @param user_id
     */
    public void setUserId(long user_id) {
        this.user_id = user_id;
    }
}